<template>
  <div>
    <div class="ml-2 flex-1">
      <div>
        <a-card :bordered="false" style="height: 830px; width: 1380px">
          <a-form :model="searchForm" layout="inline" class="mt-3" ref="searchFormRef">
            <a-form-item label="退款状态" name="refundStatus">
              <a-select v-model:value="searchForm.refundStatus" placeholder="请选择" allow-clear style="width: 150px">
                <a-select-option value="1">待退费</a-select-option>
                <a-select-option value="2">已退费</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="收费期" name="yearRange">
              <a-range-picker v-model:value="searchForm.yearRange" format="YYYY" picker="year" />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" class="mr-3" :icon="h(SearchOutlined)" @click="onSearch">查询</a-button>
              <a-button type="primary" :icon="h(RedoOutlined)" class="mr-3" @click="onReset">重置</a-button>
              <a-button :icon="h(HistoryOutlined)" @click="openModel">退费记录</a-button>
            </a-form-item>
          </a-form>
          <a-table :columns="columns" :data-source="dataSource" bordered :pagination="pagination" class="mt-5"
            :scroll="{ x: 3000, y: 550 }" :row-class-name="(_record: any, index: number) =>
              index % 2 === 1 ? 'table-striped' : null
              ">
            <template #bodyCell="{ column, record, text }">
              <template v-if="column.dataIndex === 'active'">
                <a-button type="link" @click="onOpen(record)">退费</a-button>
              </template>
            </template>
          </a-table>
        </a-card>
      </div>
    </div>
    <a-modal v-model:open="isRecord" title="退费记录" :footer="null" width="1200px">
      <a-table :columns="columns_two" :data-source="dataSource_two" bordered :pagination="pagination_two" class="mt-5"
        :row-class-name="(_record: any, index: number) =>
          index % 2 === 1 ? 'table-striped' : null
          ">
      </a-table>
    </a-modal>
    <a-drawer v-model:open="isOpen" title="退费" placement="right" size="large" :bodyStyle="{ 'padding-top': '5px' }">
      <a-divider orientation="left">基本信息</a-divider>
      <a-descriptions>
        <a-descriptions-item label="小区名称" :span="2">{{
          tableInfo.village
        }}</a-descriptions-item>
        <a-descriptions-item label="住户地址" :span="2">{{
          tableInfo.houseAddress
        }}</a-descriptions-item>
        <a-descriptions-item label="热力卡号" :span="2">{{
          tableInfo.alipayConsNo
        }}</a-descriptions-item>
        <a-descriptions-item label="房间号" :span="2">{{
          tableInfo.houseName
        }}</a-descriptions-item>
        <a-descriptions-item label="住户名称" :span="2">{{
          tableInfo.holder
        }}</a-descriptions-item>
        <a-descriptions-item label="账户编号" :span="2">{{
          tableInfo.accountNumber ?? '--'
        }}</a-descriptions-item>
      </a-descriptions>
      <a-divider orientation="left">退费信息</a-divider>
      <a-descriptions>
        <a-descriptions-item label="应收金额" :span="2">{{
          tableInfo.receivableTotal - tableInfo.receivableDerate
        }}</a-descriptions-item>
        <a-descriptions-item label="优惠金额" :span="2">{{
          tableInfo.totalDiscountMoney + tableInfo.zeroAmount
        }}</a-descriptions-item>
        <a-descriptions-item label="已交金额" :span="2">{{
          tableInfo.yjTotal
        }}</a-descriptions-item>
        <a-descriptions-item label="已退金额" :span="2">{{
          tableInfo.refundTotal
        }}</a-descriptions-item>
        <a-descriptions-item label="应退金额" :span="2">
          {{ tableInfo.shouldRefund }}
        </a-descriptions-item>
        <a-descriptions-item label="已收滞纳金" :span="2">{{
          tableInfo.lateFeeRealReceive
        }}</a-descriptions-item>
      </a-descriptions>
      <a-divider orientation="left">退费</a-divider>
      <a-form layout="inline" :label-col="labelCol" :model="tableInfo">
        <a-form-item label="退费日期">
          <a-date-picker v-model:value="tableInfo.refundDate" format="YYYY-MM-DD HH:mm:ss" style="width: 150px" />
        </a-form-item>
        <a-form-item label="退费原因">
          <a-input v-model:value="tableInfo.refundCause" style="width: 150px" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="退费接收人">
          <a-input v-model:value="tableInfo.receiver" style="width: 150px" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="退费方式">
          <a-select v-model:value="tableInfo.refundWay" placeholder="请选择" allowClear style="width: 150px">
            <a-select-option value="1">支付宝</a-select-option>
            <a-select-option value="2">微信</a-select-option>
            <a-select-option value="3">现金</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="退费类型">
          <a-select v-model:value="tableInfo.refundType" placeholder="请选择" allowClear style="width: 150px"
            @change="handleChange">
            <a-select-option value="多交退费" :disabled="tableInfo.shouldRefund <= 0">多交退费</a-select-option>
            <a-select-option value="补贴退费">补贴退费</a-select-option>
            <a-select-option value="不热退费">不热退费</a-select-option>
            <a-select-option value="滞纳金退费">滞纳金退费</a-select-option>
            <a-select-option value="退补退费">退补退费</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="费用类型" v-if="tableInfo.billingWay != '面积'">
          <a-select v-model:value="tableInfo.feeType" placeholder="请选择" allowClear style="width: 150px">
            <a-select-option value="计量费">计量费</a-select-option>
            <a-select-option value="基础费">基础费</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="实退金额">
          <a-input v-model:value="tableInfo.realBack" style="width: 150px" placeholder="请输入"
            @blur="handleRealBackChange" />
        </a-form-item>
      </a-form>
      <a-divider orientation="left">退款去向</a-divider>
      <div class="pay-mode-border">
        <div class="pay-mode-container">
          <div v-for="item in payMode" :key="item.id" class="pay-mode-item" :class="{
            'pay-mode-item-selected': tableInfo.selectedPayMode === item.id,
          }" @click="handlePayModeSelect(item)">
            <icon-font :type="item.icon" style="font-size: 30px" />
            <span>{{ item.label }}</span>
          </div>
        </div>
      </div>
      <template #footer>
        <a-button type="primary" @click="onSave" style="width: 100%">提交</a-button>
      </template>
    </a-drawer>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, h } from 'vue';
import {
  SearchOutlined,
  RedoOutlined,
  HistoryOutlined,
  createFromIconfontCN,
} from '@ant-design/icons-vue';
import {
  getRefundApi,
  getRefundRecordApi,
  getAccountBalanceApi,
  submitRefundApi,
} from '#/api/core/charge';
import dayjs from 'dayjs';
import { message } from 'ant-design-vue';
import { Decimal } from 'decimal.js';
const value = ref('1');
const labelCol = { style: { width: '100px' } };
const IconFont = createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/c/font_4920978_1xu5f6tn4o3.js',
});
const props = defineProps({
  selectedNodeId: {
    type: Array,
    default: [],
  },
});
const searchForm = reactive({
  refundStatus: '',
  yearRange: [],
});
const isRecord = ref(false);
const isOpen = ref(false);
const tableInfo = ref({});
const payMode = [
  {
    id: 1,
    label: '现金',
    icon: 'icon-jinrong-',
  },
  {
    id: 2,
    label: '预付款',
    icon: 'icon-zhuanzhang',
  },
];
const data = reactive([
  { label: '退费管理', value: '1' },
  { label: '退费记录', value: '2' },
]);
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const searchFormRef = ref(null);
const pagination_two = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination_two.current = page;
    pagination_two.pageSize = pageSize;
    openModel();
  },
});
const dataSource = ref([]);
const dataSource_two = ref([]);
const columns_two = [
  {
    title: '收费期',
    dataIndex: 'year',
    key: 'year',
    align: 'center',
  },
  {
    title: '退费时间',
    dataIndex: 'tradeDate',
    key: 'tradeDate',
    align: 'center',
  },
  {
    title: '支付编号',
    dataIndex: 'refundNo',
    key: 'refundNo',
    align: 'center',
  },
  {
    title: '退款方式',
    dataIndex: 'tradeWay',
    key: 'tradeWay',
    align: 'center',
  },
  {
    title: '退款金额',
    dataIndex: 'tradeAmount',
    key: 'tradeAmount',
    align: 'center',
  },
  {
    title: '退款天数',
    dataIndex: 'refundDays',
    key: 'refundDays',
    align: 'center',
  },
  {
    title: '退款编号',
    dataIndex: 'refundDispositon',
    key: 'refundDispositon',
    align: 'center',
  },
  {
    title: '退款人',
    dataIndex: 'receiver',
    key: 'receiver',
    align: 'center',
  },
  {
    title: '退款百分比',
    dataIndex: 'refundRate',
    key: 'refundRate',
    align: 'center',
  },
  {
    title: '退款原因',
    dataIndex: 'redAccountReason',
    key: 'redAccountReason',
    align: 'center',
  },
];
const columns = [
  {
    title: '小区名称',
    dataIndex: 'village',
    key: 'village',
    align: 'center',
  },
  {
    title: '热力卡号',
    dataIndex: 'alipayConsNo',
    key: 'alipayConsNo',
    align: 'center',
  },
  {
    title: '住户名称',
    dataIndex: 'holder',
    key: 'holder',
    align: 'center',
  },
  {
    title: '用户地址',
    dataIndex: 'houseAddress',
    key: 'houseAddress',
    align: 'center',
  },
  {
    title: '收费期',
    dataIndex: 'year',
    key: 'year',
    align: 'center',
  },
  {
    title: '收费面积',
    dataIndex: 'feeArea',
    key: 'feeArea',
    align: 'center',
  },
  {
    title: '应收全费金额',
    dataIndex: 'normalReceivable',
    key: 'normalReceivable',
    align: 'center',
  },
  {
    title: '应收基本费金额',
    dataIndex: 'heatWasteReceivable',
    key: 'heatWasteReceivable',
    align: 'center',
  },
  {
    title: '已收金额',
    dataIndex: 'yjTotal',
    key: 'yjTotal',
    align: 'center',
  },
  {
    title: '实收金额',
    dataIndex: 'realReceiveToal',
    key: 'realReceiveToal',
    align: 'center',
  },
  {
    title: '可退金额',
    dataIndex: 'shouldRefund',
    key: 'shouldRefund',
    align: 'center',
  },
  {
    title: '退款金额',
    dataIndex: 'refundTotal',
    key: 'refundTotal',
    align: 'center',
  },
  {
    title: '多交退费合计',
    dataIndex: 'djtTotal',
    key: 'djtTotal',
    align: 'center',
  },
  {
    title: '补贴/不热退费合计',
    dataIndex: 'bttTotal',
    key: 'bttTotal',
    align: 'center',
  },
  // {
  //   title: "滞纳金退费合计",
  //   dataIndex: "refundTotal",
  //   key: "refundTotal",
  //   align: "center",
  // },
  // {
  //   title: "退款转入预收款",
  //   dataIndex: "name",
  //   key: "name",
  //   align: "center",
  // },
  // {
  //   title: "退款去向",
  //   dataIndex: "name",
  //   key: "name",
  //   align: "center",
  // },
  // {
  //   title: "缴款方式",
  //   dataIndex: "name",
  //   key: "name",
  //   align: "center",
  // },
  // {
  //   title: "收费人",
  //   dataIndex: "name",
  //   key: "name",
  //   align: "center",
  // },
  // {
  //   title: "收费时间",
  //   dataIndex: "name",
  //   key: "name",
  //   align: "center",
  // },
  // {
  //   title: "缴费单位",
  //   dataIndex: "name",
  //   key: "name",
  //   align: "center",
  // },
  {
    title: '退款状态',
    dataIndex: 'refundStatus',
    key: 'refundStatus',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'active',
    key: 'active',
    align: 'center',
    fixed: 'right',
  },
];
const onSearch = () => {
  if (!props.selectedNodeId || props.selectedNodeId.length === 0) {
    message.error('请选择左侧树结构！');
    return;
  } else {
    const data = {
      headerMessage: {
        refundStatus: searchForm.refundStatus,
        yearBegin:
          searchForm.yearRange.length != 0
            ? dayjs(searchForm.yearRange[0]).format('YYYY')
            : '',
        yearEnd:
          searchForm.yearRange.length != 0
            ? dayjs(searchForm.yearRange[1]).format('YYYY')
            : '',
      },
      treeData: props.selectedNodeId,
      page: pagination.current,
      limit: pagination.pageSize,
    };
    getRefundApi(data).then((res: any) => {
      console.log(res);
      dataSource.value = res.data;
      pagination.total = res.total;
    });
  }
};
const openModel = () => {
  console.log('openModel');
  if (!props.selectedNodeId || props.selectedNodeId.length === 0) {
    message.error('请选择左侧树结构！');
    return;
  } else {
    const data = {
      headerMessage: {
        refundStatus: searchForm.refundStatus,
        yearBegin:
          searchForm.yearRange.length != 0
            ? dayjs(searchForm.yearRange[0]).format('YYYY')
            : '',
        yearEnd:
          searchForm.yearRange.length != 0
            ? dayjs(searchForm.yearRange[1]).format('YYYY')
            : '',
      },
      treeData: props.selectedNodeId,
      page: pagination_two.current,
      limit: pagination_two.pageSize,
    };
    getRefundRecordApi(data).then((res: any) => {
      console.log(res);
      isRecord.value = true;
      dataSource_two.value = res.data;
      pagination_two.total = res.total;
    });
  }

};
const onOpen = (record: any) => {
  console.log(record);

  getAccountBalanceApi(record.areaID).then((res: any) => {
    if (res) {
      tableInfo.value = { ...record, ...res };
      tableInfo.value.refundDate = dayjs();
    } else {
      tableInfo.value = { ...record };
      tableInfo.value.refundDate = dayjs();
    }
  });
  isOpen.value = true;
};
const handlePayModeSelect = (item: any) => {
  tableInfo.value.selectedPayMode = item.id;
  tableInfo.value.refundDispositon = item.label;
};
const onSave = () => {
  const data = {
    houseID: tableInfo.value.houseID,
    areaID: tableInfo.value.areaID,
    year: tableInfo.value.year,
    billingWay: tableInfo.value.billingWay,
    heatingStatus: tableInfo.value.heatingStatus,
    refundType: tableInfo.value.refundType,
    refundWay: tableInfo.value.refundWay,
    realBack: tableInfo.value.realBack,
    refundCause: tableInfo.value.refundCause,
    refundDays: '',
    refundRate: '',
    refundDispositon: tableInfo.value.refundDispositon,
    refundToPrepaid: '',
    refundDate: dayjs(tableInfo.value.refundDate).format('YYYY-MM-DD HH:mm:ss'),
    receiver: tableInfo.value.receiver,
    refundUrl: '',
    remark: '',
    feeType: tableInfo.value.feeType,
  };
  submitRefundApi(data).then((res: any) => {
    console.log(res);
    if (res) {
      message.success(res);
      onSearch();
      isOpen.value = false;
    } else {
      message.error('提交失败');
    }
  });
};
const handleChange = (e: any) => {
  console.log(e);
  if (e != '多交退费' && tableInfo.value.shouldRefund > 0) {
    message.error('请操作多交退费');
    tableInfo.value.refundType = '多交退费';
    return;
  }
};
const handleRealBackChange = (e: any) => {
  console.log(e.target.value);
  console.log(e > tableInfo.value.shouldRefund);
  if (tableInfo.value.refundType != '多交退费') {
    // 使用Decimal.js进行比较
    if (new Decimal(e.target.value).greaterThan(tableInfo.value.shouldRefund)) {
      message.error('退款金额不能大于可退金额');
      tableInfo.value.realBack = 0;
    }
  } else if (tableInfo.value.refundType == '滞纳金退费') {
    // 使用Decimal.js进行比较
    if (
      new Decimal(e.target.value).greaterThan(
        tableInfo.value.lateFeeRealReceive,
      )
    ) {
      message.error('退款金额不能大于可退金额');
      tableInfo.value.realBack = 0;
    }
  }
};
const onReset = () => {
  searchFormRef.value.resetFields();
};
</script>
<style scoped>
:deep(.ant-drawer .ant-drawer-body) {
  padding-top: 5px !important;
}

:deep(.ant-form-item) {
  margin-bottom: 10px !important;
}

.pay-mode-border {
  width: 100%;
  display: flex;
  justify-content: center;
}

.pay-mode-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.pay-mode-item {
  width: 90px;
  height: 80px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 12px;
  border: 1px dashed #1890ff;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

/* .pay-mode-item:hover {
  border-color: #006be6;
  color: #006be6;
} */

.pay-mode-item-selected {
  border-color: #006be6;
  /* background-color: #006be6;
  color: #fff; */
  border-style: solid;
}
</style>
